package com.chen.blue.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.*;

/**
 * Created By CLT On 2023/10/25.
 */
@SuppressWarnings("all")
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {


    /**
     * 解决knife4访问不了的问题
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        // 本地资源
        registry.addResourceHandler("/profile/**").addResourceLocations("file:H:\\web\\hhh\\img\\");
    }

    /**
     * 设置默认返回类型为json
     *
     * @param configurer
     */
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
    }


    /**
     * pc端和手机端接口分类
     *
     * @param configurer
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher matcher = new AntPathMatcher(".");
        // 这里的c指定是每一个controller类
        configurer.addPathPrefix("/admin", c -> {
            return c.isAnnotationPresent(RestController.class) && matcher.match("**.controller.admin.**", c.getPackage().getName());
        });
        configurer.addPathPrefix("/app", c -> {
            return c.isAnnotationPresent(RestController.class) && matcher.match("**.controller.app.**", c.getPackage().getName());
        });
    }


    /**
     * 跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/admin/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowedOriginPatterns("*");
    }
}
